package models

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"weekly-exam-practice/addconfig"
)

var DB *gorm.DB

func Init() {
	var err error
	MysqlConfig := addconfig.Config.Mysql
	dsn := fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=utf8mb4&parseTime=True&loc=Local",
		MysqlConfig.User,
		MysqlConfig.Password,
		MysqlConfig.Host,
		MysqlConfig.Port,
		MysqlConfig.Database,
	)
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		fmt.Println(err)
		panic("数据库连接失败")
	}
	fmt.Println("数据库连接成功")
	err = DB.AutoMigrate(&Article{})
	if err != nil {
		fmt.Println(err)
		panic("数据表迁移失败")
	}
	fmt.Println("数据表迁移成功")
}
